package com.em.sugarfight.util;

import com.em.sugarfight.entity.*;
import com.em.sugarfight.sugarEnums.Direction;
import com.em.sugarfight.sugarEnums.TerrainEnum;

import java.util.Arrays;

public class AdjustPositionUtil {
    public static MoveCommand adjustMyPosition(GameState gameState,DangerMap dangerMap){
        PlayerStateVo myPlayer = gameState.getMy_player();
        PixelPosition pixelPosition = myPlayer.getPosition();
        Position position = CoordinateConverter.pixelToGrid(pixelPosition);
        boolean inDanger = dangerMap.isInDanger(position);

        if(pixelPosition.getX() % 25  != 0){
            int gap = pixelPosition.getX() - position.getX() * 50 + 25;
            if(gap > 12.5){
                return new MoveCommand("L",false,gap);
            }else {
                return new MoveCommand("R",false,gap);
            }
        }else {
            int gap = pixelPosition.getY() - position.getY() * 50 + 25;
            if(gap > 12.5){
                return new MoveCommand("D",false,gap);
            }else {
                return new MoveCommand("U",false,gap);
            }
        }
    }

    public static boolean needToAdjust(GameState gameState,PixelPosition position){
//        Cell[][] map = gameState.getMap();
//        Position currentPos = CoordinateConverter.pixelToGrid(position);
        // 搜索相邻位置
//        boolean flag = false;
//        for (Direction dir : Arrays.asList(Direction.U, Direction.D, Direction.L, Direction.R)) {
//            Position next = currentPos.move(dir);
//            if(!isValidPosition(next,gameState))
//                continue;
//            TerrainEnum nextTerrain = map[next.getY()][next.getX()].getTerrain();
//
//            if(position.getX() % 25 != 0 && (dir.equals(Direction.L) || dir.equals(Direction.R)) && (nextTerrain.equals(TerrainEnum.I) || nextTerrain.equals(TerrainEnum.N))){
//                flag = true;
//            }else if (position.getY() % 25 != 0 && (dir.equals(Direction.U) || dir.equals(Direction.D)) && (nextTerrain.equals(TerrainEnum.I) || nextTerrain.equals(TerrainEnum.N)))
//                flag = true;
//
//            if(flag)
//                break;
//        }
//        return flag;
        return position.getX() % 25 != 0 || position.getY() % 25 != 0;
    }

    private static boolean isValidPosition(Position pos, GameState gameState) {
        Cell[][] map = gameState.getMap();
        int x = pos.getX(), y = pos.getY();

        if (x < 0 || x >= map[0].length || y < 0 || y >= map.length) {
            return false;
        }

        Cell cell = map[y][x];
        String terrain = cell.getTerrain().name();
        return !"I".equals(terrain) && !"N".equals(terrain) && !"D".equals(terrain);
    }
}
